package cn.tedu._03vehicle.base.filters;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    //过滤器初始化的方法,一般不使用;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("过滤器初始化");
    }

    //过滤器的核心方法,用于实现:权限校验、网站限流、访问日志、限定访问时间等等;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入登录状态校验的过滤器...");
        /*
            1.获取会话对象;
            2.获取用户标识;
            3.判断用户标识是否为null;
         */
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO != null){ //已登录
            //如果有该行代码,则放行;
            //如果无该行代码,则不放行;
            filterChain.doFilter(request, response);
        } else {//未登录
            response.sendRedirect("/login.html");
        }
    }

    //过滤器销毁的方法,一般不使用;
    @Override
    public void destroy() {
        log.debug("过滤器销毁");
    }
}
